﻿using AutoMapper;
using MediatR;
using Traceability.API.Applications.Command.PictureCommand;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.API.Applications.CommandHandler.PictureCommandHandler
{
    public class PictureAddCommandHandler : IRequestHandler<PictureAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Picture> _pictureRepository;
        private readonly IMapper mapper;

        public PictureAddCommandHandler(IBaseRepository<Picture> pictureRepository, IMapper mapper)
        {
            _pictureRepository = pictureRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(PictureAddCommand request, CancellationToken cancellationToken)
        {
           var model = mapper.Map<Picture>(request);
            model.CreateTime = DateTime.Now;
           var count= await _pictureRepository.Add(model);
            APIResult<int> aPIResult = new APIResult<int>();
            if (count > 0)
            {
                aPIResult.Code = EnumCode.Ok;
                aPIResult.Data = count;
                aPIResult.Msg = "添加成功";
            }
            else
            {
                aPIResult.Code = EnumCode.File;
                aPIResult.Data = count;
                aPIResult.Msg = "添加失败";
            }
            return await Task.FromResult(aPIResult);
            

        }
    }
}
